from pymongo import MongoClient
import json


def obj_to_json(obj):
    return json.dumps(obj)


def json_to_obj(json_str):
    return json.loads(json_str)


def get_mongo_client(uri="mongodb://centos.server:27017"):
    try:
        mongo_client = MongoClient(uri)
        mongo_client.admin.command("ping")
        print("成功连接到MongoDB服务器")
        return mongo_client
    except Exception as e:
        print(e)
        return None


client = get_mongo_client()
if client:
    db = client["mydatabase"]
    collection = db["mycollection"]
    # content = {"name": "John Doe", "age": 30}
    # content_str = obj_to_json(content)
    # document = {"content": content_str, "memoryId": "alm"}
    # result = collection.insert_one(document)
    # print(f"插入的文档的ID是: {result.inserted_id}")

    result = collection.find_one({"memoryId": "alm"})
    content_str = result["content"]
    content = json_to_obj(content_str)
    name = content.get("name")
    print(f"查询到的文档内容是: {name}")


